package com.kehongborui.client;

import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;

/**
 * @author zhang peng yang ming
 * @CopyRight (C) http://www.csdn.com
 * @brief
 * @email 122162005@qq.com
 * @date 2018-09-30
 */
public class Client extends WebSocketClient {
    public static Client client;

    private Client(URI uri, Draft_6455 draft) {
        super(uri, draft);
    }

    @Override
    public void onOpen(ServerHandshake arg0) {
        System.out.println("打开链接");
    }

    @Override
    public void onMessage(String arg0) {
        System.out.println("收到服务端消息"+arg0);
    }

    @Override
    public void onError(Exception arg0) {
        arg0.printStackTrace();
        System.out.println("发生错误已关闭");
    }

    @Override
    public void onClose(int arg0, String arg1, boolean arg2) {
        System.out.println("链接已关闭");
    }

    @Override
    public void onMessage(ByteBuffer bytes) {
        try {
            System.out.println(new String(bytes.array(),"utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取web socket 客户端
     * @param url
     * @return
     * @throws URISyntaxException
     * @throws UnsupportedEncodingException
     */
    public static Client getClient(String url) throws URISyntaxException, UnsupportedEncodingException {
        if (client == null) {
            synchronized (Client.class) {
                if (client == null) {
                    client = new Client(new URI(url), new Draft_6455());
                }

                // 建立链接
                client.connect();

                //判断是否链接成功
                while(!client.getReadyState().equals(WebSocket.READYSTATE.OPEN)){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("还没有打开");
                }
            }
        }

        return client;
    }

    public static void main(String[] args) throws UnsupportedEncodingException, URISyntaxException {
//        Client client = getClient("ws://localhost:80/field/temperature");
        Client client = getClient("ws://localhost:8887");
        System.out.println("打开了");
        client.send("hello world".getBytes("utf-8"));
        client.send("hello world1111");
        client.send("hello world1中国");
        System.out.println("=============>");
        while (true);
    }
}
